/* Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api.samples.greetings.client.selector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Widget;

import java.util.Iterator;

/**
 * A section in the UI. The section has a header/title and a container box
 * with widgets.
 *
 * @author Shishir Birmiwal
 */
public class ItemSection extends Composite
implements HasWidgets {

  public static interface ItemSectionCallback {
    public void expanded();
    public void collapsed();
  }

  @UiField
  FocusPanel titleFocusPanel;

  @UiField
  InlineLabel title;

  @UiField
  InlineHTML expandNote;

  @UiField
  FlowPanel container;

  private ItemSectionCallback cb;

  private static ItemSectionUiBinder uiBinder = GWT
      .create(ItemSectionUiBinder.class);

  interface ItemSectionUiBinder extends UiBinder<Widget, ItemSection> {
  }

  public ItemSection() {
    initWidget(uiBinder.createAndBindUi(this));
  }

  public void setCallback(ItemSectionCallback cb) {
    this.cb = cb;
  }

  public void setTitle(String text) {
    this.title.setText(text);
  }

  @UiHandler("titleFocusPanel")
  public void onClick(ClickEvent event) {
    if (container.isVisible()) {
      collapse();
    } else {
      expand();
    }
  }

  public void collapse() {
    expandNote.setHTML("&nbsp;&raquo;");
    container.setVisible(false);
    if (cb != null) {
      cb.collapsed();
    }
  }

  public void expand() {
    expandNote.setHTML("");
    container.setVisible(true);
    if (cb != null) {
      cb.expanded();
    }
  }

  @Override
  public void add(Widget arg0) {
    container.add(arg0);
  }

  @Override
  public void clear() {
    container.clear();
  }

  @Override
  public Iterator<Widget> iterator() {
    return container.iterator();
  }

  @Override
  public boolean remove(Widget arg0) {
    return container.remove(arg0);
  }
}
